package cn.tedu.smartos.base.utils.user.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 缓存工具类
 */
@Component
public class CacheUtil {
    @Autowired
    private RedisTemplate<String,Serializable> redisTemplate;

    public void set(String key, Serializable value) {
        redisTemplate.opsForValue().set(key, value);
    }

    public void setExpire(String key, Serializable value, long timeout) {
        redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
    }

    public Serializable get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public boolean del(String key) {
        return redisTemplate.delete(key);
    }
    /**
     * 根据前缀删除缓存 key
     */
    public void delByPrefix(String prefix) {
        Set<String> keys = redisTemplate.keys(prefix + "*");
        if (keys != null && !keys.isEmpty()) {
            redisTemplate.delete(keys);
        }
    }
    /**
     * 设置缓存并设置过期时间
     */
    public void setExpire(String key, Serializable value, int seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }
}
